<?php
namespace app\admin\model;
use think\Model;

class SystemNav extends Model {
	
	protected $name = 'system_nav';  			//表名
	protected $pk = 'nav_id';  			//主键		
	protected $autoinc  = true;	   	    //主键是否自动增长类型
   
    protected $insert = ['func_code','sort'];
    protected function setFuncCodeAttr() {
        return $this->max('func_code') + 1;
    }
    protected function setSortAttr($value) {
        return $value ?: $this->where('sort','<','900')->max('sort') + 1;
    }
   
	//获取导航数据
	public function getNavData(){
	    $userInfo = request()->userInfo;
		$sql = "
			SELECT a.nav_id,a.func_code,a.nav_name, 
			a.nav_url, a.nav_status,a.nav_pid,a.sort,a.icon,    
			(	
				SELECT group_concat(b.action_code) 
				FROM xw_system_nav_action as b WHERE b.nav_id = a.nav_id
			) as action_code,
			(
			    SELECT action FROM xw_system_group WHERE org_id=:orgId
			) as user_org_action
			FROM xw_system_nav  as a 
		";
        if($userInfo['user_code'] == 'administrator'){
            //$sql.=" where a.nav_status=-1 or a.nav_name in ('开发工具','代码生成器','ICON图标')";
        }else{
            $sql.=" where a.nav_status !=-1 and a.nav_name not in ('开发工具','代码生成器','ICON图标')";
        }
        if($userInfo['shop_id'] ==0){
			$sql.=" and a.nav_name not in ('本店商品列表','总店商品列表')";
		}else{
			$sql.=" and a.nav_name not in ('商品列表')";
		}
        
        $sql.=' ORDER BY LPAD(a.sort,4,0) asc';
		return \Db::query($sql,['orgId'=>$userInfo['org_id']]);
	}
	
	//根据路由获取导航 func_code
	public function getNavAuthCode($url){
		$data = ['func_code'=>'','action_code'=>''];
		$rerult = $this->where('nav_url',$url)->find();
		if( !empty($rerult) ){
			$data['func_code'] = $rerult['func_code'];
			$list = model("SystemNavAction")->where('nav_id',$rerult['nav_id'])->column('action_code');
			$data['action_code'] =   join(",",$list);
		}
		return $data;
	}
	
	//更新排序 
	public function updateSort($moveId,$coverId){
		$rerult = $this->saveAll( [
		    ['nav_id'=>$moveId, 'sort'=> $this->where('nav_id',$coverId)->value('sort') ],
		    ['nav_id'=>$coverId, 'sort'=> $this->where('nav_id',$moveId)->value('sort') ]
		] );
		return $rerult;
	}
	
	/**
     * 启用或禁用
     * @param array $data 
     * @return type
     */
	public function setEnable($data)
    {
		return $this->allowField('nav_status')->saveAll($data);
    }
	
	
}